package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.LoginMapper;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public UserVo login(LoginDto loginDto) {
        User user = loginMapper.selectByUserName(loginDto.getUsername());
        // 判断用户是否存在
        if (ObjectUtil.isEmpty(user)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        // 判断用户是否禁用
        if (user.getDataState().equals(SuperConstant.DATA_STATE_1)) {
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        // 判断密码是否正确
        if (!BCrypt.checkpw(loginDto.getPassword(), user.getPassword())) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        // 转换成Vo
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        // 脱敏
        userVo.setPassword("");

        // 获取用户 有权限的资源列表
        List<Resource> resources = resourceMapper.selectListByUserId(userVo.getId());
        List<String> urlList = resources.stream().map(r -> r.getRequestPath()).collect(Collectors.toList());

        // 获取白名单资源
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        // 合并路径
        urlList.addAll(publicAccessUrls);

        // 存储到Redis中
        redisTemplate.opsForValue().set(CacheConstant.PUBLIC_ACCESS_URLS + userVo.getId(),
                JSONUtil.toJsonStr(urlList), jwtTokenManagerProperties.getTtl() / 1000,
                TimeUnit.SECONDS);

        Map<String, Object> claims = new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(user));
        // 生成token
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(),
                claims);
        userVo.setUserToken(token);
        return userVo;
    }
}
